﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using System.Threading;
using System.Timers;
using ZK.InterfaceServer;
using ZK.HardWareBLL;

namespace ZK.YHP_TransManage.UC
{
    public partial class InCoal : UserControl
    {

        public CameraBLL cameraQ;
        public CameraBLL cameraG;
        HardWareBLL.Onbon6K1CardBLL Onbon6K1CardBLL;
        private HardWareBLL.YRTReaderBLL yRTReaderBLL;
        HardWareBLL.NRNetRelayBLL nRNetRelayBLL;
        LingShengAudioBLL lingShengAudio;
        System.Timers.Timer rePeatCardNumTimer =
           new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("RePeatCardNumTime")));
        public string cardNumNow = string.Empty;
        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.GetTruckYxInfoRceiveM yxYsTransportReturnDto;
        int clearTextTime;
        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();
        private static readonly object obj = new object();
        /// <summary>
        /// 构造函数 d
        /// </summary>
        public InCoal()
        {
            InitializeComponent();

            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
        }

        /// <summary>
        /// 初始化led
        /// </summary>
        private void InitLed()
        {
            //int a = Onbon6E1XCardBLL.InitSdk();
            //LedShow(Com.TipsStringHelper.gldchyn);
            Onbon6K1CardBLL = new HardWareBLL.Onbon6K1CardBLL();
            LedPageShow(Com.TipsStringHelper.Hyy);
        }
        /// <summary>
        /// 初始化菱声网络音响
        /// </summary>
        private void InitLingSheng()
        {
            lingShengAudio = new LingShengAudioBLL();
        }
        /// <summary>
        /// led显示消息
        /// </summary>
        /// <param name="str"></param>
        private void LedShow(string str)
        {
            Onbon6K1CardBLL.SCREEN_SendDynamicArea(str);
        }

        /// <summary>
        /// 提示信息现在在led，页面上。
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShow(string str)
        {
            LedShow(str);
            PageShow(str);
        }

        /// <summary>
        /// 将异常信息显示的led page上， 并记录错误日志。
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShowLog(Exception ex)
        {
            LedShow(ex.Message);
            PageShow(ex.Message);
            Common.Log4.LogManage.WriteErr(ex.ToString());
        }

        /// <summary>
        /// 提示信息的最大长度
        /// </summary>
        private int InfoMaxLength = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLength"));
        /// <summary>
        /// 在显示在页面中的提示信息的长度超过的个数，截取的比例
        /// </summary>
        private int InfoMaxLengthCut = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLengthCut"));

        /// <summary>
        /// 提示信息显示在页面上
        /// </summary>
        /// <param name="str"></param>
        private void PageShow(string str)
        {
            //lock (obj)
            //{
            this.Invoke(new Action(() =>
            {
                // textBoxInfo.tex
                int leg = textBoxInfo.TextLength;
                string infoTest = textBoxInfo.Text;
                if (leg > InfoMaxLength)
                {
                    infoTest = infoTest.Substring(leg / InfoMaxLengthCut);
                    textBoxInfo.Text = infoTest;
                }
                textBoxInfo.AppendText("--" + str + "\n");
            }));


        }

        int InOutClearTextTime = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InOutClearTextTime"));

        /// <summary>
        /// 间隔时间清空数据
        /// </summary>
        //private void ClearTextTime()
        //{
        //    Task.Factory.StartNew(new Action(() =>
        //    {
        //        // Thread.Sleep(InOutClearTextTime);
        //        // MessageShowInPage(InOutClearTextTime + "毫秒后，清空页面！");
        //        ClearText();
        //    }));
        //}

        /// <summary>
        /// 设置页面数据
        /// </summary>
        private void SetText()
        {
            if (string.IsNullOrWhiteSpace(yxYsTransportReturnDto.cardNo))
            {
                return;
            }
            this.Invoke(new Action(() =>
            {
                textBoxKZT.Text = Enum.GetName(typeof(SysDefinitionEnum.SendType), yxYsTransportReturnDto.sendType);
                textBoxCYS.Text = yxYsTransportReturnDto.carrierName;
                textBoxGSMC.Text = yxYsTransportReturnDto.shipperName;
                textBoxHWMC.Text = yxYsTransportReturnDto.coalName;
                textBoxBZ.Text = yxYsTransportReturnDto.memo;
                textBoxLX.Text = Enum.GetName(typeof(SysDefinitionEnum.YxState), yxYsTransportReturnDto.yxState);
            }));
        }



        private void InOut_Load(object sender, EventArgs e)
        {
            MyInit();
        }

        private void MyInit()
        {

            // PageShow("page load success");
            clearTextTime = Convert.ToInt32(AppConfigHelper.GetAppSettings("ClearTextTime"));
            DelegateHelper.InfoMessageEvent += PageShow;
            DelegateHelper.CameraGetCarNumEvent += CameraGetCarNum;

            InitCamera();
            InitLed();
            InitLingSheng();
            InitRead();
            InitTimer();
            InitNetworkRelay();
            yRTReaderBLL.getDataCallbackEvent = GetReadDataCallback;

            Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;


        }
        /// <summary>
        /// 初始化网络继电器
        /// </summary>
        private void InitNetworkRelay()
        {
            nRNetRelayBLL = new HardWareBLL.NRNetRelayBLL();
        }

        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }

        private void InitTimer()
        {
            rePeatCardNumTimer.Elapsed += RePeatCardNumTimer_Elapsed;
            rePeatCardNumTimer.Enabled = true;
            rePeatCardNumTimer.AutoReset = false;
            rePeatCardNumTimer.Start();
        }

        private void RePeatCardNumTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
        }

        private void InitRead()
        {
            yRTReaderBLL = new HardWareBLL.YRTReaderBLL();
            //yRTReaderBLL.getDataCallbackEvent = GetReadDataCallback;
        }
        /// <summary>
        /// 在页面设置卡号
        /// </summary>
        void SetCardNum(string str)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCardNum.Text = str;
            }));
        }
        /// <summary>
        /// 读卡器数据的回调
        /// </summary>
        /// <param name="epc"></param>
        private void GetReadDataCallback(string epc)
        {
            lock (obj)
            {
                string reaStr = epc.Substring(0, 12);
                SetCardNum(reaStr);
                if (cardNumNow == epc)
                {
                    if (rePeatCardNumTimer.Enabled)
                    {
                        PageShow("当前卡号重复，倒计时还在继续！");
                    }
                    else
                    {
                        if (epc.Length != 12)
                        {
                            LedPageShow(epc);
                            return;
                        }
                        DoSomthing();
                    }
                }
                else
                {
                    cardNumNow = epc;
                    if (epc.Length != 12)
                    {
                        LedPageShow(epc);
                        return;
                    }
                    LedPageShow("当前卡号：" + reaStr);
                    DoSomthing();
                }
            }
        }
        /// <summary>
        /// 查询并判断流程
        /// </summary>
        void DoSomthing()
        {
            try
            {
                rePeatCardNumTimer.Stop();
                rePeatCardNumTimer.Start();
                //if (!rePeatCardNumTimer.Enabled)
                //{
                //    rePeatCardNumTimer.Start();
                //}
                string cardNum = textBoxCardNum.Text.Trim();
                string carNum = textBoxCarNum.Text.Trim();

                Models.GetTruckYxInfoSendM getTruckYxInfoSendM = new Models.GetTruckYxInfoSendM()
                {
                    cardNo = cardNum,
                    truckNo = carNum
                };

                var resGetTruckYxInfo = AutoControlTransportApiServer.GetTruckYxInfo(getTruckYxInfoSendM);
                if (resGetTruckYxInfo == null)
                {
                    MessageThrow();
                }
                if (!resGetTruckYxInfo.success)
                {
                    MessageThrow(resGetTruckYxInfo.msg);
                }
                yxYsTransportReturnDto = resGetTruckYxInfo.data == null ? new Models.GetTruckYxInfoRceiveM() : resGetTruckYxInfo.data;
                SetText();

                //获取监控的图片
                List<string> picCodeList = new List<string>();
                string imgs1;
                string picG1 = cameraG.UpLoadFile();
                if (!string.IsNullOrWhiteSpace(picG1))
                {
                    picCodeList.Add(picG1);
                }
                imgs1 = string.Join(",", picCodeList);

                //*****验证车牌是否可以入矿
                Models.TruckIntoCoalmineSendM sendM = new Models.TruckIntoCoalmineSendM()
                {
                    cardNo = cardNum,
                    truckNo = carNum,
                    imgs1 = imgs1
                };
                Models.ReceiveDataBase<object> receiveDataBase = AutoControlTransportApiServer.TruckIntoCoalmine(sendM);
                if (receiveDataBase == null)
                {
                    MessageThrow();
                }
                if (!receiveDataBase.success)
                {
                    MessageThrow(receiveDataBase.msg);
                }
                LedPageShow(receiveDataBase.msg);
                lingShengAudio.AutoStartTask(Convert.ToInt32(AppConfigHelper.GetAppSettings("LingShengTaskIdYZTG")));//验证通过
                // cameraQ.BarrierGateControl(1);
                bool res = nRNetRelayBLL.HandleStach(1);
                if (!res)
                {
                    Common.Log4.LogManage.WriteErr("网络继电器控制道闸开启失败！");
                }
                ClearText();
            }
            catch (Exception ex)
            {
                LedPageShowLog(ex);
                if (ex.Message.Contains("车卡不一致"))
                {
                    lingShengAudio.AutoStartTask(Convert.ToInt32(AppConfigHelper.GetAppSettings("LingShengTaskIdCKBYZ")));
                }
                //if (ex.Message.Contains("未查询到绑定"))
                //{
                //    lingShengAudio.AutoStartTask(Convert.ToInt32(AppConfigHelper.GetAppSettings("LingShengTaskIdWBD")));
                //}
                if (ex.Message.Contains("未派车"))
                {
                    lingShengAudio.AutoStartTask(Convert.ToInt32(AppConfigHelper.GetAppSettings("LingShengTaskIdWPC")));
                }
                //this.Invoke(new Action(() =>
                //{
                //    textBoxCardNum.Text = "";
                //}));
            }
        }

        /// <summary>
        /// 清除页面数据
        /// </summary>
        private void ClearText()
        {
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(clearTextTime);
                this.Invoke(new Action(() =>
                {
                    textBoxKZT.Text = "";
                    textBoxCYS.Text = "";
                    textBoxGSMC.Text = "";
                    textBoxHWMC.Text = "";
                    textBoxBZ.Text = "";
                    textBoxLX.Text = "";
                    textBoxCarNum.Text = "";
                    textBoxCardNum.Text = "";
                }));
                yxYsTransportReturnDto = new Models.GetTruckYxInfoRceiveM();
                LedPageShow(Com.TipsStringHelper.Hyy);
            });



        }

        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="str"></param>
        void MessageThrow(string str)
        {
            throw new Exception(str);
        }
        void MessageThrow()
        {
            throw new Exception("接口调用异常或超时");
        }

        private void CameraGetCarNum(string carNum, string cameraIp)
        {
            Common.Log4.LogManage.WriteInfo("称重页面拿到了车牌:" + carNum + " 摄像头ip：" + cameraIp);
            SetCarNumInPage(carNum);
            LedPageShow("当前车牌：" + carNum);
            //DoSomthing();
        }

        void SetCarNumInPage(string carNum)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCarNum.Text = carNum;
            }));
        }

        private void InitCamera()
        {
            //Q
            {
                Common.HaredWareCommonM cameraScalesQ = Common.IConfig.GetSetCameraScalesQ;
                Common.CameraModel cameraModelQ = new Common.CameraModel()
                {
                    Name = cameraScalesQ.Name,
                    Ip = cameraScalesQ.Ip,
                    Port = Convert.ToInt32(cameraScalesQ.Port),
                    PassWord = cameraScalesQ.PassWord,
                    UserName = cameraScalesQ.UserName
                };
                PageShow("cameraModelQ 初始化");
                cameraQ = new CameraBLL(cameraModelQ);
                cameraQ.ManualOne(pictureBoxQ);
            }

            //G1
            {
                Common.HaredWareCommonM cameraScalesG1 = Common.IConfig.GetSetCameraScalesG1;
                Common.CameraModel cameraModelG1 = new Common.CameraModel()
                {
                    Ip = cameraScalesG1.Ip,
                    Name = cameraScalesG1.Name,
                    Port = Convert.ToInt32(cameraScalesG1.Port),
                    PassWord = cameraScalesG1.PassWord,
                    UserName = cameraScalesG1.UserName
                };
                PageShow("cameraModelG1 初始化");
                cameraG = new CameraBLL(cameraModelG1);
                cameraG.ManualOne(pictureBoxG);
            }
        }

    }
}
